﻿<template>
  <view class="content">
    <view class="hall-gallery">
      <image :src="galleryIntro?.poster" mode="aspectFill" class="gallery-image"></image>
    </view>
    <view class="hall-intro">
      <up-sticky bgColor="#fff" customNavHeight="0" zIndex="10">
        <up-tabs :list="hallIntroTabs" @click="click" :scrollable="false" @change="onTabChange"></up-tabs>
      </up-sticky>
      <view class="tab-content">
        <view v-if="currentTab === 0">
          <view class="exhibition-name" v-if="galleryDetail?.data?.galleryName">
            <text class="exhibition-name-text">{{ galleryDetail.data.galleryName }}</text>
          </view>
          <view class="host-info" v-if="galleryDetail?.data?.host">
            <text class="host-label">举办方：</text>
            <text class="host-name">{{ galleryDetail.data.host }}</text>
          </view>
          <up-read-more :toggle="true" ref="uReadMoreRef" showHeight="200" @load="load" class="intro-read-more">
            <view class="intro-content">
              <u-parse :content="galleryIntro?.description" class="h-content"></u-parse>
            </view>
          </up-read-more>
          <view class="h-comment-list">
            <!-- 评论插件 -->
            <common-comment :data="commentDataForComponent" :user-id="userInfo.id || 'user123'" :display-count="3"
              @like="handleLike" @delete="handleDelete" @submit="handleSubmit" @view-all="handleAllCommentClick" @validate-user="handleValidateUser"/>
          </view>
        </view>
        <view v-if="currentTab === 1">
          <view class="search-container">
            <up-search v-model="searchKeyword" placeholder="搜索作品名称或作者" clearabled @search="handleSearch" shape="square"
              :showAction="false"></up-search>
          </view>
          <view class="works-list">
            <up-waterfall v-model="filteredWorks" ref="uWaterfallRef" :columns="2">
              <template v-slot:column="{ colList, colIndex }">
                <view v-for="(artwork, index) in colList" :key="artwork.id" class="work-item">
                  <image :src="artwork.coverImage" mode="widthFix" class="work-image"
                    @click="goToArtworkDetail(artwork.artworkId)" />
                  <view class="work-info">
                    <text class="work-name">{{ artwork.title }}</text>
                    <text class="work-author">{{ artwork.artistName }}</text>
                  </view>
                </view>
              </template>
            </up-waterfall>
          </view>
          <view class="empty-state" v-if="filteredWorks.length === 0">
            <text>暂无相关作品</text>
          </view>
        </view>
      </view>
    </view>
  </view>
  <!-- 底部功能区 -->
  <view class="bottom-bar">
    <up-icon name="share" size="24" @click="handleShare" labelPos="right" :label="shareCount"></up-icon>
    <up-icon name="heart" size="24" @click="handleCollect" labelPos="right"
      :label="galleryDetail?.data.likeCount || 0"></up-icon>
    <!-- <view class="action-btn">
      <up-button text="进入展厅" color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
        @click="handleEnterHall"></up-button>
    </view> -->
  </view>

  <up-popup :show="showAllComments" :round="10" mode="bottom" closeable @close="closeAllComments"
    :safe-area-inset-bottom="true" :zoom="true" :custom-style="{
      zIndex: 9998,
      height: '85vh',
      maxHeight: '85vh',
      display: 'flex',
      flexDirection: 'column',
    }">
    <all-comment :data="commentPageDataForComponent" :user-id="userInfo.id || 'user123'" @like="handleLike"
      @delete="handleDelete" @submit="handleSubmit" @load-more="handleLoadMoreComments" />
  </up-popup>

  <up-popup :show="show" :round="10" mode="bottom" @close="close" @open="open">
    <view class="share-popup">
      <view class="popup-header">
        <text class="share-title">分享展览</text>
        <up-icon name="close" size="20" @click="close" class="close-icon"></up-icon>
      </view>

      <view class="share-preview">
        <image :src="shareData.imageUrl" class="preview-image" mode="aspectFill"></image>
        <view class="preview-info">
          <text class="preview-title">{{ shareData.title }}</text>
          <text class="preview-desc">{{ shareData.desc }}</text>
        </view>
      </view>

      <view class="share-grid">
        <!-- #ifdef MP-WEIXIN -->
        <view class="share-item" hover-class="share-item-hover">
          <button class="share-btn" open-type="share" @click="handleMiniShare">
            <view class="share-icon-wrapper wechat">
              <up-icon name="weixin" size="28" color="#fff"></up-icon>
            </view>
            <text>微信好友</text>
          </button>
        </view>
        <!-- #endif -->

        <!-- #ifndef MP-WEIXIN -->
        <view class="share-item" @click="shareToWeChat" hover-class="share-item-hover">
          <view class="share-icon-wrapper wechat">
            <up-icon name="weixin" size="28" color="#fff"></up-icon>
          </view>
          <text>微信好友</text>
        </view>
        <!-- #endif -->

        <view class="share-item" @click="shareToMoments" hover-class="share-item-hover">
          <view class="share-icon-wrapper moments">
            <up-icon name="moments" size="28" color="#fff"></up-icon>
          </view>
          <text>朋友圈</text>
        </view>

        <view class="share-item" @click="copyLink" hover-class="share-item-hover">
          <view class="share-icon-wrapper link">
            <up-icon name="link" size="28" color="#fff"></up-icon>
          </view>
          <text>复制链接</text>
        </view>
      </view>

      <view class="share-cancel" @click="close">取消</view>
    </view>
  </up-popup>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { usePagination, useRequest } from 'alova/client'
import { onLoad } from "@dcloudio/uni-app";
import CommonComment from "../components/common-comment.vue";
import AllComment from "../components/all-comments-list.vue";
import Apis from '@/api/index.js';
import { isLogin ,validateToken} from '@/utils/auth.js';

// 当前用户ID
const userInfo = reactive({});
const showAllComments = ref(false);

// 页面生命周期
onMounted(async () => {
  // 页面加载时的逻辑，可根据需要补充
  load();
});

// 分页查询
const {
  data: commentList, // 数据
  total: commentTotal_1, // 总条数
  refresh
} = usePagination((page, pageSize) => Apis.wx_comment.treeComment({
  params: { pageNum: page, pageSize: pageSize, targetId: galleryId.value || '1' }
}), {
  initialData: { // 初始数据
    total: 0,
    data: []
  },
  preloadNextPage: false, // 关闭预加载下一页数据
  immediate: true, // 是否立即执行，默认为true
  append: false, // 是否追加数据，默认为false
  initialPage: 1, // 初始页码，默认为1
  initialPageSize: 10, // 初始每页数据条数设置为3
  total: res => res.total, // 从响应中获取总量（默认取total字段）
  data: res => res.rows, // 从数据中获取data（默认取data字段）
});

// 获取页面参数
const galleryId = ref(null);
// 监听页面加载
onLoad(async (options) => {
  console.log("页面参数:", options);
  if (options.galleryId) {
    galleryId.value = options.galleryId;
    // 加载展厅详情
    await send();
    await nextTick();
    if (uReadMoreRef.value) {
      uReadMoreRef.value.init();
    }
  }
});

// 获取展厅详情
const { data: galleryDetail, loading, error, send } = useRequest(
  () => Apis.wx_gallery.getGalleryInfo({
    pathParams: { galleryId: galleryId.value }
  }),
  {
    immediate: false, // 初始时不立即执行
  }
);

const galleryIntro = computed(() => {
  console.log("galleryDetail:", galleryDetail.value);
  if (!galleryDetail.value) {
    return {
      poster: "",
      description: "暂无展馆介绍"
    };
  }
  return {
    poster: galleryDetail?.value.data.poster || "",
    description: galleryDetail?.value.data.description || "暂无展馆介绍"
  };
});
// 分享数据
const shareData = computed(() => {
  if (!galleryDetail.value) {
    return {
      title: "",
      desc: "",
      path: "",
      imageUrl: ""
    };
  }
  return {
    title: galleryDetail?.value?.data?.galleryName || "",
    desc: galleryDetail?.value?.data?.description || "",
    path: `/pages/gallery/detail?galleryId=${galleryDetail?.value?.data?.id}`,
    imageUrl: galleryDetail?.value?.data?.poster || ""
  }

});

// 为评论组件准备数据结构
const commentDataForComponent = computed(() => {
  return {
    total: commentTotal_1 || 0,
    list: commentList || []
  };
});

// 为评论组件准备数据结构
const commentPageDataForComponent = computed(() => {
  return {
    isLastPage: isLastPage || false,
    isLoadingMore: false,
    page: commentPage_2 || 1,
    total: commentTotal_2 || 0,
    list: commentPageData || []
  };
});

const {
  data: commentPageData, // 数据
  isLastPage, // 根据total和size计算，如果没有total根据当前页数据是否满足size判断
  total: commentTotal_2, // 总条数
  page: commentPage_2, // 当前页码
  pageCount, // 总页数
  loading: commentLoading, // 加载状态
  send: sendComment,
  reload,
  refresh: paginationRefresh
} = usePagination((page, pageSize) => Apis.wx_comment.treeComment({
  params: { pageNum: page, pageSize: pageSize, targetId: galleryId.value || '1' }
}), {
  initialData: { // 初始数据
    total: 0,
    data: []
  },
  cache: false,
  preloadNextPage: false, // 关闭预加载下一页数据
  immediate: false, // 是否立即执行，默认为true
  append: true, // 是否追加数据，默认为false
  initialPage: 1, // 初始页码，默认为1
  initialPageSize: 10, // 初始每页数据条数设置为10
  total: res => res.total, // 从响应中获取总量（默认取total字段）
  data: res => res.rows, // 从数据中获取data（默认取data字段）
})

const refreshComments = () => {
  refresh();
  paginationRefresh();
};

const handleLoadMoreComments = async (data) => {
  console.log("加载更多评论:", data);
  if (!isLastPage.value) {
    console.log("最后一页:", data);
    commentPage_2.value = data.page + 1
  }
};


const handleValidateUser = () => {
  // 验证用户登录状态的逻辑
  if(isLogin() && validateToken()){
    return true;
  }
  uni.showModal({
    title: '提示',
    content: '您尚未登录，请先登录',
    success: function (res) {
      if (res.confirm) {
        console.log('用户点击确定');
        uni.navigateTo({
          url: '/pages/login/index'
        });
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  });
  return false;
};

// 处理点赞评论
const handleLike = async (data) => {
  console.log("点赞主评论:", data);
  const response = await Apis.wx_comment.likeComment({ data: data });
  if (response && response.code === 200) {
    uni.showToast({
      title: "点赞成功",
      icon: "success"
    });
    refreshComments()
  } else {
    uni.showToast({
      title: response.msg || "点赞失败",
      icon: "none"
    });
  }
};

// 处理删除评论
const handleDelete = async (data) => {
  console.log("删除主评论:", data);
  const response = await Apis.wx_comment.deleteComment({ data: data });
  if (response && response.code === 200) {
    uni.showToast({
      title: "删除成功",
      icon: "success"
    });
    refreshComments()
  } else {
    uni.showToast({
      title: response.msg || "删除失败",
      icon: "none"
    });
  }
};

// 处理提交评论（主页面）
const handleSubmit = async (data) => {
  console.log("提交评论:", data);
  // 构造评论数据对象
  const commentParams = {
    content: data.content,
    targetId: galleryId.value, // 使用实际的展品ID
    parentId: data.parentId || null,
    rootId: data.rootId || 0,
    userId: userInfo.id, // 这里应该使用实际的用户ID
    // 其他需要的字段可以根据ExhiComment接口定义添加
  };
  // 调用API提交评论
  const response = await Apis.wx_comment.addComment({ data: commentParams });
  if (response && response.code === 200) {
    uni.showToast({
      title: "评论提交成功",
      icon: "success"
    });
    refreshComments()
  } else {
    uni.showToast({
      title: response.msg || "评论失败",
      icon: "none"
    });
  }
};

const handleAllCommentClick = () => {
  console.log("点击了查看全部评论");
  showAllComments.value = true;
  reload()
  sendComment()
};

function closeAllComments() {
  // 关闭逻辑，设置 show 为 false
  showAllComments.value = false;
  // console.log('close');
}
// 分享次数
const shareCount = ref(1);
// 收藏个数
const collectCount = ref(2);
// 添加对up-read-more的引用
const uReadMoreRef = ref(null);

const currentTab = ref(0);

const hallIntroTabs = reactive([
  { name: "展览主题", id: 0 },
  { name: "作品展示", id: 1 },
]);

// 获取展厅作品列表
const {
  data: artworkList,
  loading: artworkLoading,
  send: sendArtworkList
} = useRequest(
  () => Apis.wx_gallery.getGalleryArtworkList({
    params: { galleryId: galleryId.value }
  }),
  {
    immediate: false, // 初始时不立即执行
    initialData: [] // 初始数据为空数组
  }
);

// 作品列表数据（从接口获取）
const worksList = computed(() => {
  // 处理接口返回的数据，确保格式正确
  if (artworkLoading.value || !artworkList.value || !artworkList.value.data) {
    return [];
  }
  // 映射接口数据到前端需要的格式
  return artworkList.value.data;
});

// tab切换处理函数
function onTabChange(index) {
  // 更新当前选中的tab索引
  currentTab.value = index.index;
  if (index.index === 1) {
    sendArtworkList();
  }
}

// 搜索关键词
const searchKeyword = ref("");

// 过滤后的作品列表
const filteredWorks = computed(() => {
  if (!searchKeyword.value) return worksList.value;
  const filtered = worksList.value.filter(
    (work) =>
      work.title.includes(searchKeyword.value) ||
      work.artistName.includes(searchKeyword.value)
  );
  if (filtered.length === 0) {
    uni.showToast({ title: "未找到相关作品", icon: "none" });
  }
  return filtered;
});

// 添加对up-waterfall的引用
const uWaterfallRef = ref(null);

// 修改搜索处理函数
const handleSearch = (value) => {
  searchKeyword.value = value;
  // 如果需要额外的搜索逻辑可以在这里添加
};

// 底部功能按钮逻辑
const handleShare = () => {
  open();
};

// #ifdef MP-WEIXIN
// 处理小程序分享按钮点击
const handleMiniShare = () => {
  close();
  shareCount.value++;
  uni.showToast({ title: "分享成功", icon: "success", duration: 1500 });
  // 小程序会自动调用 onShareAppMessage 方法
};
// #endif

// 分享到微信好友
const shareToWeChat = () => {
  close();
  // #ifdef MP-WEIXIN
  // 小程序中提示用户使用右上角分享
  uni.showModal({
    title: "分享提示",
    content: "请点击右上角「···」按钮，选择「发送给朋友」进行分享",
    showCancel: false,
    confirmText: "知道了",
  });
  // #endif

  // #ifndef MP-WEIXIN
  uni.getProvider({
    service: "share",
    success: (res) => {
      if (res.provider.includes("weixin")) {
        uni.share({
          provider: "weixin",
          scene: "WXSceneSession",
          type: 0,
          title: shareData.title,
          summary: shareData.desc,
          imageUrl: shareData.imageUrl,
          success: () => {
            shareCount.value++;
            uni.showToast({
              title: "分享成功",
              icon: "success",
              duration: 1500,
            });
          },
          fail: (err) => {
            console.error("分享失败:", err);
            uni.showToast({ title: "分享失败", icon: "error" });
          },
        });
      } else {
        uni.showToast({ title: "未安装微信", icon: "none" });
      }
    },
    fail: () => {
      uni.showToast({ title: "获取分享服务失败", icon: "none" });
    },
  });
  // #endif
};

// 分享到朋友圈
const shareToMoments = () => {
  close();
  // #ifdef MP-WEIXIN
  uni.showModal({
    title: "分享提示",
    content: "请点击右上角「···」按钮，选择「分享到朋友圈」进行分享",
    showCancel: false,
    confirmText: "知道了",
  });
  // #endif

  // #ifndef MP-WEIXIN
  uni.getProvider({
    service: "share",
    success: (res) => {
      if (res.provider.includes("weixin")) {
        uni.share({
          provider: "weixin",
          scene: "WXSceneTimeline",
          type: 0,
          title: shareData.title,
          summary: shareData.desc,
          imageUrl: shareData.imageUrl,
          success: () => {
            shareCount.value++;
            uni.showToast({
              title: "分享成功",
              icon: "success",
              duration: 1500,
            });
          },
          fail: (err) => {
            console.error("分享失败:", err);
            uni.showToast({ title: "分享失败", icon: "error" });
          },
        });
      } else {
        uni.showToast({ title: "未安装微信", icon: "none" });
      }
    },
    fail: () => {
      uni.showToast({ title: "获取分享服务失败", icon: "none" });
    },
  });
  // #endif
};

// 复制链接
const copyLink = () => {
  close();
  const shareUrl = `https://your-domain.com${shareData.path}`;
  uni.setClipboardData({
    data: shareUrl,
    success: () => {
      uni.showToast({ title: "链接已复制", icon: "success", duration: 1500 });
    },
    fail: () => {
      uni.showToast({ title: "复制失败", icon: "error" });
    },
  });
};

const handleCollect = () => {
  uni.showToast({ title: "收藏功能开发中", icon: "none" });
};
const handleEnterHall = () => {
  const externalUrl =
    "https://shishuhuayin.com.cn/exhibition/1/babylon-exhibition";
  uni.navigateTo({
    url: `/pages/webview/webview?url=${encodeURIComponent(externalUrl)}`,
  });
};

// 跳转到作品详情页?
const goToArtworkDetail = (artworkId) => {
  uni.navigateTo({
    url: `/gallery_pages/artwork/artwork-detail?artworkId=${artworkId}`,
  });
};

// #ifdef MP-WEIXIN
// 微信小程序分享配置
const onShareAppMessage = () => {
  return {
    title: shareData.title,
    desc: shareData.desc,
    path: shareData.path,
    imageUrl: shareData.imageUrl || galleryIntro?.poster,
  };
};

const onShareTimeline = () => {
  return {
    title: shareData.title,
    query: "from=timeline",
    imageUrl: shareData.imageUrl || galleryIntro?.poster,
  };
};

// 暴露给小程序使用
defineExpose({
  onShareAppMessage,
  onShareTimeline,
});
// #endif

// 创建响应式数据
const show = ref(false);

// 定义方法
function open() {
  // 打开逻辑，比如设置 show 为 true
  show.value = true;
  console.log("分享数据", shareData);
}

function close() {
  // 关闭逻辑，设置 show 为 false
  show.value = false;
  // console.log('close');
}

function load() {
  // 加载逻辑
  if (uReadMoreRef.value) {
    uReadMoreRef.value.init();
  }
}

</script>

<style lang="scss" scoped>
.content {
  padding-bottom: 100rpx;
}

.hall-gallery {
  position: relative;
}

.gallery-image {
  width: 100%;
  height: 400rpx;
  display: block;
}

.indicator-num {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
  padding: 8rpx 16rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 100rpx;
  color: #ffffff;
  font-size: 24rpx;
  z-index: 10;
}

.hall-intro {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  // margin-top: -10rpx;
  position: relative;
  z-index: 2;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx 0;
}

.h-content {
  padding: 0;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
}

.intro-read-more {
  margin: 20rpx 30rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
}

.intro-content {
  padding: 30rpx;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
}

.h-comment-list {
  padding: 0 30rpx 30rpx;
}

.tab-content {
  min-height: 600rpx;
}

.search-container {
  padding: 20rpx 30rpx;
  background: #f8f9fa;
}

.works-list {
  padding: 20rpx 30rpx;
}

.work-item {
  margin-bottom: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.work-image {
  width: 100%;
  height: auto;
  display: block;
}

.work-info {
  padding: 20rpx;
}

.work-name {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.work-author {
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0 50rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
}

.action-btn {
  flex: 1;
  margin-left: 30rpx;
}

.share-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 0;
  margin: 0;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.share-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.close-icon {
  padding: 10rpx;
}

.share-preview {
  padding: 30rpx;
  display: flex;
  align-items: flex-start;
  border-bottom: 1rpx solid #f0f0f0;
}

.preview-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.preview-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 120rpx;
}

.preview-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
  margin-bottom: 10rpx;
}

.preview-desc {
  font-size: 24rpx;
  color: #999;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.share-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  padding: 40rpx 30rpx;
}

.share-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.share-btn {
  background: none;
  border: none;
  padding: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.share-icon-wrapper {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.wechat {
  background: #07c160;
}

.moments {
  background: #ffcc00;
}

.link {
  background: #1890ff;
}

.share-item text {
  font-size: 24rpx;
  color: #666;
}

.share-item-hover {
  opacity: 0.7;
}

.share-cancel {
  text-align: center;
  padding: 30rpx;
  font-size: 32rpx;
  color: #999;
  border-top: 1rpx solid #f0f0f0;
}

.host-info {
  padding: 20rpx 30rpx;
  background-color: #f8f9fa;
  border-radius: 10rpx;
  margin: 20rpx 30rpx;
  display: flex;
  align-items: center;
}

.host-label {
  font-weight: bold;
  color: #333;
  font-size: 28rpx;
}

.host-name {
  color: #666;
  font-size: 26rpx;
}

.exhibition-name {
  padding: 10rpx 30rpx;
  background-color: #fff;
  border-radius: 10rpx;
  margin: 10rpx 30rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.exhibition-name-text {
  font-weight: bold;
  color: #333;
  font-size: 32rpx;
}
</style>